const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wh: null,
    cookie: "",
    orderType: "",
    mate: [
      {
        title: "未使用",
        orderType: 1
      },
      {
        title: "已使用",
        orderType: 2
      },
      {
        title: "已过期",
        orderType: 0
      }
    ],
    mateArray: [],
    _yhqtypr:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '优惠券'
    })
    this.setData({
      orderType: 1,
      _yhqtypr: options.num
    })
    try {
      var res = wx.getSystemInfoSync();
      this.setData({
        wh: res.windowHeight + 'px'
      })

    } catch (e) {
      // Do something when catch error
      console.log(e)
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var self = this;
    var a = wx.getStorageSync('cookie') || [];
    this.setData({
      cookie: a,
      mateArray: []
    })
    this.orderTf({ currentTarget:{
      dataset:{
        ty:1
      }
    }})
  },
  orderTf: function (e) {
    var self = this;
    this.setData({
      orderType: e.currentTarget.dataset.ty,
      mateArray: []
    })
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/xcx_switch2",
      data: {
        stat: self.data.orderType
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + this.data.cookie
      },
      method: "POST",
      success: (res) => {
        wx.hideLoading();
        const data = res.data;
        let orderArr = [];
        if (data){
          for(let i=0; i<data.length; i++){
            if(JSON.stringify(data[i]) != "{}"){
              let t1 = new Date(data[i].startTime), t2 = new Date(data[i].endTime),t = new Date(),time = "";
              if (self.diffDays(t,t2) == 0){
                time = "即将过期";
              } else if (self.diffDays(t, t2) < 0){
                time = "已过期";
              } else {
                time = "还有" + self.diffDays(t, t2) + "天";
              }
              
              if (self.data.orderType == 1 && self.diffDays(t, t2) >= 0){
                orderArr.push({
                  _id:data[i]._id,
                  gzms:data[i].gzms,
                  json:JSON.stringify(data[i]),
                  addCommodity: (data[i].addCommodity.length > 0 ? '仅针对部分商品' : '全场通用'),
                  name: (data[i].yhtj_name == "yhtj_002" ? "全场通用" : "满" + data[i].yhtj + "元可用"),
                  yhj: data[i].yhj,
                  period: t1.getFullYear() + '/' + (t1.getMonth() + 1) + '/' + t1.getDate() + '-' + t2.getFullYear() + '/' + (t2.getMonth() + 1) + '/' + t2.getDate()
                })
              } else if (self.data.orderType == 2){
                orderArr.push({
                  gzms: data[i].gzms,
                  addCommodity: (data[i].addCommodity.length > 0 ? '仅针对部分商品' : '全场通用'),
                  name: (data[i].yhtj_name == "yhtj_002" ? "全场通用" : "满" + data[i].yhtj + "元可用"),
                  yhj: data[i].yhj,
                  period: t1.getFullYear() + '/' + (t1.getMonth() + 1) + '/' + t1.getDate() + '-' + t2.getFullYear() + '/' + (t2.getMonth() + 1) + '/' + t2.getDate()
                })
              } else if (self.data.orderType == 0 && self.diffDays(t, t2) < 0){
                orderArr.push({
                  gzms: data[i].gzms,
                  addCommodity: (data[i].addCommodity.length > 0 ? '仅针对部分商品' : '全场通用'),
                  name: (data[i].yhtj_name == "yhtj_002" ? "全场通用" : "满" + data[i].yhtj + "元可用"),
                  yhj: data[i].yhj,
                  period: t1.getFullYear() + '/' + (t1.getMonth() + 1) + '/' + t1.getDate() + '-' + t2.getFullYear() + '/' + (t2.getMonth() + 1) + '/' + t2.getDate()
                })
              }

              
            }
          }
          self.setData({
            mateArray: orderArr
          })
        }else{
          var a ="您暂时还未获得优惠券!"
        }
      },
      fail: (res) => {
        wx.hideLoading();
        console.log(res)
      }
    })
  },
  /*点击使用优惠劵 */
  yhjsy(res){
    const id = res.currentTarget.dataset.id,json = app.globalData._json,
      val = res.currentTarget.dataset.value, gzms = res.currentTarget.dataset.gzms;
    let tj = {},arr = [];  
    if (this.data._yhqtypr == "1"){
      for (let i = 0; i < json.length; i++){
        arr.push(json[i][0])
      }
      tj.goodsList = arr;
      wx.request({
        url: "https://csb2c.fenxiangqu.cn/xcx_use_coupons",
        data: {
          id :id,
          q:encodeURIComponent(JSON.stringify(tj))
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': "LID=" + this.data.cookie
        },
        method: "POST",
        success: res => {
          if(res.data){
            const data = res.data,json = JSON.parse(val);
            let yhtj_name = json.yhtj_name, yhfa_name = json.yhfa_name;
            let newJson = data[0], json_price = data[1];
            let allPrice = app.globalData.all_price;
            if (yhtj_name == "yhtj_001"){
              if (yhfa_name == "yhff_001") {//免运费
                app.globalData._by = true;
                app.globalData.yhj = '包邮';
              } else if (yhfa_name == "yhff_002") {//满金额减价格
                app.globalData._by = false;
                app.globalData.yhj = parseFloat(newJson.yhfa).toFixed(2);
              } else if (yhfa_name == "yhff_003") {//满金额打折
                app.globalData._by = false;
                app.globalData.yhj = json_price;
              }
            }else{
              if (newJson.yhfa_name == "yhff_001"){
                app.globalData._by = true;
                app.globalData.yhj = '包邮';
              } else if (newJson.yhfa_name == "yhff_002"){
                app.globalData._by = false;
                app.globalData.yhj = parseFloat(newJson.yhfa).toFixed(2);
              } else if (newJson.yhfa_name == "yhff_003"){
                app.globalData._by = false;
                app.globalData.yhj = ((+app.globalData.all_price) - ((+app.globalData.all_price) * (+newJson.yhfa)/10)).toFixed(2)
              }
            }
            app.globalData.yhjtext = gzms;
            if (app.globalData._by){
              app.globalData.yun_price = "0.00";
              app.globalData.yhj = app.globalData.yhj;
              app.globalData.yhje = app.globalData.yhje;
              app.globalData.all_price = app.globalData.all_price;
              app.globalData.orderallprice = app.globalData.all_price;
            }else{
              app.globalData.yun_price = app.globalData.yun_price;
              app.globalData.yhj = app.globalData.yhj;
              app.globalData.all_price = app.globalData.all_price;
              app.globalData.orderallprice = (+((+(app.globalData.all_price))) - +app.globalData.yhje -+app.globalData.yhj + +app.globalData.yun_price).toFixed(2);
            }
            app.globalData.user_yhq = id;
            app.globalData.yyyyy="1"
            wx.navigateBack()
          }else{
            wx.showToast({
              title: '抱歉！您未能达到领取条件',
              icon: 'success',
              duration: 1000
            })
          }
        },
        fail: res => {
          console.log(res)
        }
      })
    }
    
  },
  //计算相差的天数
  diffDays(s1, s2){
    let days= s2.getTime() - s1.getTime();
    let time = parseInt(days / (1000 * 60 * 60 * 24));
    return time;
  },
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})